//
//  ARNewFeatureController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/3/25.
//

import UIKit
import SnapKit

class ARNewFeatureController: ARBaseViewController, UIScrollViewDelegate {

    private var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .clear
        self.setupView()
    }

    private func setupView() {
        
        self.view.addSubview(self.contentView)
        self.contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        // 创建图片，并子线程解压
        let imagePaths = [
            Bundle.main.path(forResource: "new_feature_0", ofType: "heic")!,
            Bundle.main.path(forResource: "new_feature_1", ofType: "heic")!,
            Bundle.main.path(forResource: "new_feature_2", ofType: "heic")!
        ]
        
        var imageViewArray: [UIImageView] = []
        for i in 0..<imagePaths.count {
            // 创建imageview
            
            let lastView = imageViewArray.last
            let isLast = i == imagePaths.count - 1
            
            let imageView = UIImageView()
            imageView.contentMode = .scaleToFill
            
            self.contentView.addSubview(imageView)
            imageView.snp.makeConstraints { make in
                make.bottom.top.equalToSuperview()
                make.height.equalTo(ARHelper.screenHeight())
                make.width.equalTo(ARHelper.screenWidth())
                if let lastView = lastView {
                    make.left.equalTo(lastView.snp.right)
                } else {
                    make.left.equalToSuperview()
                }
                if isLast {
                    // 最后一个
                    make.right.equalToSuperview()
                }
            }
            imageViewArray.append(imageView)
            
            // 点击事件
            let btn = UIButton(type: .custom)
            btn.backgroundColor = .clear
            btn.addTarget(self, action: #selector(onNextBtnClick(_:)), for: .touchUpInside)
            contentView.addSubview(btn)
            btn.snp.makeConstraints { make in
                make.left.right.equalTo(imageView)
                make.height.equalTo(68)
                make.bottom.equalTo(imageView).offset(-(ARHelper.screenHeight() * (104.0 / 812.0)))
            }
        }
        
        // 子线程解压图片
        DispatchQueue.global().async {
            for (index, path) in imagePaths.enumerated() {
                if let image = UIImage(contentsOfFile: path) {
                    UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
                    image.draw(at: CGPoint.zero)
                    let decompressedImage = UIGraphicsGetImageFromCurrentImageContext()
                    UIGraphicsEndImageContext()

                    // 切回主线程更新 UI
                    DispatchQueue.main.async {
                        // 在这里更新你的 UI，比如给一个 UIImageView 设置图片
                        let imageView = imageViewArray[index]
                        imageView.image = decompressedImage
                    }
                }
            }
        }
        
        // 开始定时器
        startTimer()
    }
    
    @objc private func onNextBtnClick(_ sender: UIButton) {
        
        // 判断当前index
        let index = Int(contentView.contentOffset.x / ARHelper.screenWidth())
        if index < 0 || index > 2{
            return
        }
        if index == 2 {
            // 跳转下一个界面
            ARAppLauncher.share.transitionToLoginPage()
            return
        }
        contentView.setContentOffsetX(ARHelper.screenWidth() * CGFloat(index + 1), animated: true)
    }
    
    // MARK: - UIScrollViewDelegate
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        endTimer() // 取消定时器
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollViewDidEndScroll()
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        scrollViewDidEndScroll()
    }
    
    private func scrollViewDidEndScroll() {
        let index = Int(contentView.contentOffset.x / ARHelper.screenWidth())
        if index < 0 || index >= 2 {
            return
        }
        startTimer()
    }
    
    // MARK: -
    
    private func startTimer() {
        endTimer()
        
        timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(timerCallback), userInfo: nil, repeats: false)
    }
    
    private func endTimer() {
        timer?.invalidate()
        timer = nil
    }
    
    @objc private func timerCallback() {
        endTimer()
        let index = Int(contentView.contentOffset.x / ARHelper.screenWidth())
        if index < 0 || index >= 2{
            return
        }
        contentView.setContentOffsetX(ARHelper.screenWidth() * CGFloat(index + 1), animated: true)
    }
    
    // MARK: - Lazy
    
    private lazy var contentView: UIScrollView = {
        let view = UIScrollView()
        view.backgroundColor = .clear
        view.isPagingEnabled = true
        view.bounces = false
        view.delegate = self
        return view
    }()
    
}
